package org.zwt.server;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class ServerThread implements Runnable {
    private Socket socket;

    @Override
    public void run() {
        /*
         * 有时请求无真正的输入,所以可以直接抛弃
         * */
        InputStream is = null;
        try {
            is = socket.getInputStream();
            if (is.available() <= 0) {
                return;       //结束执行
            }
            /*
             * 1.解析请求,获取开始行,请求头,请求体
             * */
            this.parseReq(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                this.socket.shutdownInput();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        /*
         *2.生成响应,包括开始行、响应头、响应体
         * */
        String resp = this.generateResp();
        /*
         * 3.返回响应到客户端
         * */
        OutputStream os = null;
        try {
            os = socket.getOutputStream();
            os.write(resp.getBytes());
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                this.socket.shutdownOutput();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        /*
         * 4.关闭socket
         * */
        try {
            this.socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void parseReq(InputStream is) throws IOException {
        /*
         * 1.从InputStream获取数据
         * */
        int len = is.available();
        byte[] buffer = new byte[len];
        is.read(buffer);

        String req = new String(buffer);
        System.out.println("接收到的请求内容");
        System.out.println(req);
        /*
         * 2.拆解请求中的内容
         * */
//      请求体
        String[] split = req.split("\r\n\r\n");
        String body = null;
        if (split.length > 1) {
            body = split[1];
        }
//      开始行
        String[] lines = split[0].split("\r\n");
        String[] starts = split[0].split(" ");

        if (starts.length >= 3) {
            System.out.println("请求方法为:" + starts[0]);
            System.out.println("请求路径为:" + starts[1]);
            System.out.println("Http协议版本为:" + starts[2]);
        }
//      请求头
        Map<String, String> headers = new HashMap<>();
        if (starts.length >= 2) {
            for (int i = 1; i < lines.length; i++) {
                String[] eles = lines[i].split(": ");
                if (eles.length >= 2) {
                    headers.put(eles[0], eles[1]);
                }
            }
        }

        System.out.println("请求头内容为:");
        headers.forEach((k, v) -> System.out.println(k + ":" + v));
    }

    private String generateResp() {
        String content = "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + "    <meta charset=\"UTF-8\">\n" + "    <title>Index</title>\n" + "<link rel=\"icon\"href=\"data:;base64,=\">" + "</head>\n" + "<body>\n" + "    <h1>这是首页</h1>\n" + "</body>\n" + "</html>";
//      构建响应的格式
        StringBuilder sb = new StringBuilder();
//      开始行
        sb.append("HTTP/1.1 200 OK\r\n");
//      添加响应头
        sb.append("Server: MyServer\r\n");
        sb.append("Date: " + new Date() + "\r\n");
        sb.append("Content-Type: text/html; charset=UTF-8\r\n");
//        sb.append("Content-Length: " + content.length() + "\r\n");
        sb.append("Content-Length: " + content.getBytes().length + "\r\n");
        sb.append("\r\n");
//      添加响应体
        sb.append(content);
//      返回
        return sb.toString();
    }
}


